package cn.lwj.webService.client;

import cn.lwj.webService.entity.DataJzbView;
import cn.lwj.webService.entity.DataJzbViewList;
import cn.lwj.webService.entity.XmlResult;
import cn.lwj.webService.interceptor.SOAPHeaderInterceptor;
import cn.lwj.webService.service.DrdcManager;
import cn.lwj.webService.util.XmlUtils;
import cn.lwj.webService.util.XmlXStreamUtils;
import cn.net.withub.webservice.client.rdjzbSjyw.SjywWebService;
import java.io.IOException;
import java.io.StringReader;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.apache.cxf.endpoint.Client;
import org.apache.cxf.frontend.ClientProxy;
import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;
import org.apache.cxf.transport.http.HTTPConduit;
import org.apache.cxf.transports.http.configuration.HTTPClientPolicy;
import org.apache.log4j.Logger;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.Namespace;
import org.jdom2.input.SAXBuilder;
import org.springframework.stereotype.Service;
import org.xml.sax.InputSource;

@Service(value = "sjzxClient")
public class SjzxClient {



    private Logger log = Logger.getLogger(this.getClass());

    @Resource
    private DrdcManager drdcManager;

    public Object createFactoryBean(Class<?> myClass) throws Exception {
        JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();
        factory.setServiceClass(myClass);
        factory.getOutInterceptors().add(new SOAPHeaderInterceptor("000", "0000", "000000withub"));
        //System.out.println(compro.SJJZB_WEBSERVICE_URL + "?wsdl");
        String wsdl_url = "http://149.0.45.31:8087/hlj/services/sjyw?wsdl?wsdl";
        factory.setAddress(wsdl_url);
        return factory.create();
    }

    //setClient("webService");
    public void setClient(Object obj) {
        Client proxy = ClientProxy.getClient(obj);
        HTTPConduit conduit = (HTTPConduit) proxy.getConduit();
        HTTPClientPolicy httpClientPolicy = new HTTPClientPolicy();
        httpClientPolicy.setConnectionTimeout(120000); //毫秒
        httpClientPolicy.setAllowChunking(false);
        httpClientPolicy.setReceiveTimeout(120000);
        conduit.setClient(httpClientPolicy);
    }

    public XmlResult importJzbxx(String jzbId, String fydm) throws Exception {
        SjywWebService sjywWebService = (SjywWebService) createFactoryBean(SjywWebService.class);
        setClient(sjywWebService);

        DataJzbView jzbView = drdcManager.dataJzbSet(jzbId, fydm, "push", DataJzbView.YQSQ);
        String requestXml = XmlXStreamUtils.objectToXml(1, jzbView, DataJzbView.aliasInfo);
        //requestXml = XtptClient.readFile("D:\\ajxx.txt");
        log.info("请求导入信访信息[" + new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()) + "]...\r\n" + requestXml);//+requestXml
        String responseXml = "";
        responseXml = sjywWebService.importJzbxx(requestXml);
        //String responseXml = sjywWebService.importJzbxx(requestXml);
        log.info("返回导入信访信息[" + new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()) + "]...\r\n" + responseXml);
        //Map<String, String> returnMap = new HashMap<String, String>();
        //returnMap.put("flag", parseFlag(responseXml));
        //returnMap.put("exception", parseException(responseXml));
        return (XmlResult) XmlXStreamUtils.xmlToObject(responseXml, XmlResult.aliasInfo);

    }

    public DataJzbView exportJzbxx(String jzbId, String fydm) throws Exception {
        SjywWebService sjywWebService = (SjywWebService) createFactoryBean(SjywWebService.class);
        setClient(sjywWebService);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("jzbId", jzbId);
        //map.put("ywlx", DataJzbView.JDFK);
        map.put("ywlx", "");
        String requestXml = XmlUtils.createXml(map);
        //DataJzbView jzbView = drdcManager.dataJzbSet(jzbId, fydm, "push");
        //String requestXml = XmlXStreamUtils.objectToXml(1, jzbView, DataJzbView.aliasInfo);
        //requestXml = XtptClient.readFile("D:\\ajxx.txt");
        log.info("请求导出信访信息[" + new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()) + "]...\r\n" + requestXml);//+requestXml
        String responseXml = "";
        responseXml = sjywWebService.exportJzbxx(requestXml);
        DataJzbView dataJzbView = (DataJzbView) XmlXStreamUtils.xmlToObject(responseXml, DataJzbView.aliasInfo);
        //String responseXml = sjywWebService.importJzbxx(requestXml);
        log.info("返回导入信访信息[" + new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()) + "]...\r\n" + responseXml);
        //Map<String, String> returnMap = new HashMap<String, String>();
        //returnMap.put("flag", parseFlag(responseXml));
        //returnMap.put("exception", parseException(responseXml));
        return dataJzbView;

    }

    public DataJzbViewList batchExportJzbxx(String fydm) throws Exception {

        SjywWebService sjywWebService = (SjywWebService) createFactoryBean(SjywWebService.class);
        setClient(sjywWebService);
        //map.put("ywlx", DataJzbView.JDFK);
        //DataJzbViewList jzbViewList = drdcManager.dataJzbListSet(fydm);
        //String requestXml = XmlXStreamUtils.objectToXml(1, jzbView, DataJzbView.aliasInfo);
        //requestXml = XtptClient.readFile("D:\\ajxx.txt");
        //log.info("请求导出信访信息[" + new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()) + "]...\r\n" + requestXml);//+requestXml
        String responseXml = "";//batchExportJzbxx
        responseXml = sjywWebService.batchExportJzbxx();
        DataJzbViewList jzbViewList = (DataJzbViewList) XmlXStreamUtils.xmlToObject(responseXml, DataJzbViewList.aliasInfo);
        //String responseXml = sjywWebService.importJzbxx(requestXml);
        log.info("返回导入信访信息[" + new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()) + "]...\r\n" + responseXml);
        //Map<String, String> returnMap = new HashMap<String, String>();
        //returnMap.put("flag", parseFlag(responseXml));
        //returnMap.put("exception", parseException(responseXml));
        return jzbViewList;

    }
    /**
     * 解析返回的状态
     * @author LiuYang
     * @param responseXml
     * @return
     */
    private static String parseFlag(String responseXml){
        String flag = "0";
        //创建一个新的字符串
        StringReader read = new StringReader(responseXml);
        //创建新的输入源SAX 解析器将使用 InputSource 对象来确定如何读取 XML 输入
        InputSource source = new InputSource(read);
        //创建一个新的SAXBuilder
        SAXBuilder sb = new SAXBuilder();
        try {
            //通过输入源构造一个Document
            Document doc = sb.build(source);
            //取的根元素
            Element root = doc.getRootElement();
            //得到根元素所有子元素的集合
            List resultList = root.getChildren();
            //获得XML中的命名空间（XML中未定义可不写）
            Namespace ns = root.getNamespace();
            Element et = null;
            for(int i=0;i<resultList.size();i++){
                et = (Element) resultList.get(i);//循环依次得到子元素

                if(et.getName().equals("flag")){
                    flag = et.getText();
                }
            }

        } catch (JDOMException e) {
            // TODO 自动生成 catch 块
            e.printStackTrace();
        } catch (IOException e) {
            // TODO 自动生成 catch 块
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * 解析返回的异常
     * @author LiuYang
     * @param responseXml
     * @return
     */
    private static String parseException(String responseXml){
        String exception = "";
        //创建一个新的字符串
        StringReader read = new StringReader(responseXml);
        //创建新的输入源SAX 解析器将使用 InputSource 对象来确定如何读取 XML 输入
        InputSource source = new InputSource(read);
        //创建一个新的SAXBuilder
        SAXBuilder sb = new SAXBuilder();
        try {
            //通过输入源构造一个Document
            Document doc = sb.build(source);
            //取的根元素
            Element root = doc.getRootElement();
            //得到根元素所有子元素的集合
            List resultList = root.getChildren();
            //获得XML中的命名空间（XML中未定义可不写）
            Namespace ns = root.getNamespace();
            Element et = null;
            for(int i=0;i<resultList.size();i++){
                et = (Element) resultList.get(i);//循环依次得到子元素

                if(et.getName().equals("exception")){
                    exception = et.getText();
                }
            }

        } catch (JDOMException e) {
            // TODO 自动生成 catch 块
            e.printStackTrace();
        } catch (IOException e) {
            // TODO 自动生成 catch 块
            e.printStackTrace();
        }
        return exception;
    }
}
